package com.rtu.quartz;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rtu.dao.IProjectRtuDao;
import com.rtu.dao.IWPProjectDao;
import com.rtu.domain.ProjectRtuGatherData;
import com.rtu.domain.WPProject;
import com.rtu.utils.DBUtils;
import com.rtu.utils.JdbcUtils;
import com.rtu.utils.ResultSetMapper;

public class RtuJob {

	private static final Logger logger = LoggerFactory.getLogger(RtuJob.class);
	@Resource
	private IWPProjectDao wPProjectDao;
	@Resource
	private IProjectRtuDao projectRtuDao;
	public void synchronousRtuData() {
		JdbcUtils jdbcUtil = new JdbcUtils();
		ResultSet resultSet = null;
		try {
			List<WPProject> projectList = wPProjectDao.queryAllProject();
			for(WPProject dto : projectList) {
				 Integer maxOutId = projectRtuDao.queryMaxOutId(dto.getId());
				 if(null == maxOutId || maxOutId <= 0) {
					 maxOutId = 0;
				 }
				 String listSql = String.format(dto.getGatherDataSql(), ">" + maxOutId);
				 listSql = listSql.toUpperCase();
				 Map<String,String> dbSourceInfo = new HashMap<String,String>();
				 dbSourceInfo.put("jdbc.driver", dto.getJdbcDriver());
				 dbSourceInfo.put("jdbc.url", dto.getJdbcUrl());
				 dbSourceInfo.put("jdbc.username", dto.getJdbcUserName());
				 dbSourceInfo.put("jdbc.pwd", dto.getJdbcPassword());
				 DBUtils.initDataSource(dbSourceInfo);
				 String[] sqlArr = listSql.split("FROM");
				 String countSql = "select count(1) from  " + sqlArr[1];
				 int count = jdbcUtil.excuteQueryCount(countSql);
				 int one = count%500 > 0 ? 1:0;
				 int cnt = count/500 + one;
				 for(int i=0; i < cnt; i++) {
			         resultSet = jdbcUtil.excuteQueryResultSet(listSql  + "  LIMIT " + i*500 + " , 500", null);
			         ResultSetMapper<ProjectRtuGatherData> resultSetMapper = new ResultSetMapper<ProjectRtuGatherData>(); 
			         List<ProjectRtuGatherData> rtuList = resultSetMapper.mapRersultSetToObject(resultSet, ProjectRtuGatherData.class);
			         if(null != rtuList && rtuList.size() > 0) {
			         	for(ProjectRtuGatherData d : rtuList) {
			         		d.setProjectId(dto.getId());
			         	}
			         	projectRtuDao.batchInsert(rtuList); 
			         }
				 }
			}
		} catch (Exception e) {
			logger.info(e.getMessage());
		} finally {
			if(null != resultSet) {
				try {
					resultSet.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(null != jdbcUtil) {
				jdbcUtil.closeAll();
			}
		}

		logger.info("同步rtu=============");
	}
}
